const express = require('express');
const router = express.Router();

const sequelize = require('../configs/sequelize_config');
const bizProduct = require('../models/product_model');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.post('/create', async function(req, res, next) {
  try {
    const { body } = req;

    const result = await bizProduct.create({
      product_code: body.product_code,
      domain_type: 1
    });

    res.send({
      result
    });
  } catch (error) {
    res.send(error);
  }
});

router.get('/search', async function(req, res, next) {
  try {
    const result = await bizProduct.findAndCountAll({
      attributes: [
          'product_id', 'product_code', 'domain_type',
          [sequelize.Sequelize.fn('date_format', sequelize.Sequelize.col('created_at'), '%Y-%m-%d %H:%i:%s'), 'created_at'],
          [sequelize.Sequelize.fn('date_format', sequelize.Sequelize.col('updated_at'), '%Y-%m-%d %H:%i:%s'), 'updated_at']
      ],
      order: [
          ['product_code', 'ASC']
      ]
    });

    /*const queryStr =
        `select
         product_id, product_code, domain_type
         , date_format(created_at, '%Y-%m-%d %H:%i:%s') created_at
         , date_format(updated_at, '%Y-%m-%d %H:%i:%s') updated_at
         from biz_product order by product_code asc`;
    const result = await sequelize.query(queryStr, {type: 'SELECT'});*/

    res.send({
      result
    });
  } catch (error) {
    res.send(error);
  }
});

module.exports = router;
